﻿using MicroAmoy.Application.Busines.CustomerManage;
using MicroAmoy.Application.Code;
using System.Web;
using System.Web.Mvc;

namespace MicroAmoy.Application.Web
{
    public class OAuthAttribute : AuthorizeAttribute
    {
        private LoginMode _customMode;
        public OAuthAttribute(LoginMode Mode)
        {
            _customMode = Mode;
        }
        /// <summary>
        /// 微信授权 
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (this._customMode == LoginMode.Ignore)
            {
                return;
            }
            if (IsLogin)
            {
                return;
            }
            if (!IsValidated)
            {
                string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={1}&redirect_uri={0}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", HttpUtility.UrlDecode(HttpContext.Current.Request.Url.AbsoluteUri), Util.WeChat.Comm.Config.APPKEY);
                RedirectResult action = new RedirectResult(url);
                filterContext.Result = action;
            }
        }

        public string Code
        {
            get
            {
                return HttpContext.Current.Request.QueryString["code"];
            }
        }
        public bool IsLogin
        {
            get
            {
                return !WechatProvider.Provider.IsOverdue()
                     && WechatProvider.Provider.IsOnLine() == 1;
            }
        }
        public bool IsValidated
        {
            get
            {
                return !string.IsNullOrEmpty(Code) && new MACustomerBLL().Auth(Code);
            }
        }
    }
}